<template>
	<view>
		<view class="search-header">
			<view class="input-box">
				<image class="icon" src="../../static/image/search.png" />
				<input name="input" class="keywrod" focus="true" :value="keyword" confirm-type="search" @input="inputChange" @focus="inputFocus"
				 @confirm="onKeywordConfirm" :placeholder="defaultKeyword.keyword" />
				<image class="del" v-if="keyword" @click="clearKeyword" src="../../static/image/clear.png" />
			</view>
			<view class="right" @click="closeSearch">取消</view>
		</view>
		<view class="no-search" v-if="searchStatus == false">
			<view class="serach-keywords search-history" v-if="!(keyword.length <= 0) && (historyKeyword.length > 0)">
				<view class="h">
					<text class="title">历史记录</text>
					<image class="icon" @click="clearHistory" src="../../static/image/trash.png" />
				</view>
				<view class="b">
					<view class="item" @click="onKeywordTap" :data-keyword="item" v-for="(item, index) of historyKeyword" :key="item"
					 :data-index="index" hover-class="navigator-hover">{{item.keyword}}</view>
				</view>
			</view> 
			<view class="serach-keywords search-hot" v-if="!(keyword.length <= 0)">
				<view class="h">
					<text class="title">热门搜索</text>
				</view>
				<view class="b">
					<view :class="item.is_hot === 1 ? 'active item' : 'item'" hover-class="navigator-hover" @click="onKeywordTap"
					 :data-keyword="item.keyword" v-for="(item, index) of hotKeyword" :key="item.keyword" :data-index="index">{{item.keyword}}</view>
				</view>
			</view>
			<view class="shelper-list" v-if="!(keyword.length <= 0)">
				<view class="item" hover-class="navigator-hover" v-for="(item, index) of helpKeyword" :key="item" :data-index="index"
				 @click="onKeywordTap" :data-keyword="item">{{item.keyword}}</view>
			</view>
		</view>
		<view class="search-result" v-if="searchStatus && goodsList.length > 0">

			<color-sort-box :currentSortType="currentSortType" :currentSortOrder="currentSortOrder" :openSortFilter="openSortFilter"
			 :categoryFilter="categoryFilter" :filterCategory="filterCategory" :selectCategory="selectCategory" :dataList="goodsList">

			</color-sort-box>
		</view>
		<view class="search-result-empty" v-if="goodsList.length<=0 && searchStatus == true">
			<image class="icon" src="../../static/image/emptySearch.png" ></image>
			<text class="text">您寻找的商品还未上架</text>
		</view>
	</view>
</template>

<script>
	import colorSortBox from '@/components/color-sort-box.vue'
	import {
		mapGetters
	} from 'vuex'
	import {
		getUrl
	} from '@/common/oss.js';
	import {
		getProductKeys,
		getProductKeyHistorys,
		delProductHistory,
		getProductBycategory,
		getPage
	} from '@/api/mall/product'
	export default {
		components: {
			colorSortBox
		},
		data() {
			return {
				keyword: '',
				searchStatus: false,
				defaultKeyword: {},
				helpKeyword: [],
				historyKeyword: [],
				categoryFilter: false,
				currentSortType: 'default',
				defaultCateogryId: '',
				filterCategory: [],
				currentSortOrder: 'desc',
				loadingType: 0,
				page: 1,
				pageSize: 10,
				goodsList: [],
				hotKeyword: [],
				isFirstLoad: false,
				timer: null,
				categoryId: null,
				sort: "desc",
				orderBy: "RECOMMENDATION"
			}
		},
		onLoad(e) {
			this.getSearchKeyword(1, 1);
			this.getSearchKeyword(2, 10);
			this.getSearchKeywordHistory();
			if (e.type == 1) {
				this.isFirstLoad = true;
				this.categoryId = e.navigateValue;

			}

		},
		onUnload() {
			this.searchStatus = false;
		},
		computed: {
			...mapGetters(
				["hasLogin", "userId"],
			),
		},
		methods: {
			// 键盘回车进行搜索
			onKeywordConfirm: function(event) {
				// console.log('键盘回车的event', event);
				// 这里是target不是currentTarget哦~
				this.getSearchResult(event.target.value);
			},
			// “分类”的点击事件
			selectCategory: function(event) {
				// console.log('分类点击的event', event);
				let currentIndex = event.currentTarget.dataset.categoryIndex;
				this.categoryFilter = false;
				this.categoryId = this.filterCategory[currentIndex].id;
				this.getGoodList();
			},
			getSearchKeyword: function(relevancyWeight, limit) {
				let params = {
					relevancyWeight: relevancyWeight,
					page: 1,
					limit: limit,
					orderBy: "createdStamp",
					sort: "desc"
				}
				getProductKeys(params).then(response => {
					console.log("productKeys:" + JSON.stringify(response))
					if (response.status == 200 && response.data.length > 0) {
						if (relevancyWeight == 0)
							this.defaultKeyword = response.data[0]
						else
							this.hotKeyword = this.hotKeyword.concat(response.data)
					}
				});

			},
			getSearchKeywordHistory: function() {
				if (this.hasLogin == true) {
					getProductKeyHistorys({
						partyId: this.userId,
						page: 1,
						limit: 10,
						orderBy: "createdStamp",
						sort: "desc"
					}).then(res => {
						console.log("history" + JSON.stringify(res))
						if (res.status == 200 && res.data.length > 0)
							this.historyKeyword = res.data;
					})
				}
			},
			getGoodList: function(t) {
				this.historyKeyword = [];
				var that = this;
				let query = {};
				if (this.keyword.length > 0) {
					query.productName = this.keyword;
					//#ifdef APP-PLUS
					query.deviceType = plus.os.name
					//#endif
					//#ifdef MP-WEIXIN
					query.deviceType = "WEIXIN"
					//#endif
					//#ifdef H5
					query.deviceType = "H5"
					//#endif
					query.userId = this.userId;

				}
				query.page = this.page;
				query.limit = this.pageSize;
				query.orderBy = this.orderBy;
				query.sort = this.sort;

				if (this.categoryId != null && this.categoryId !== -1) {
					getProductBycategory(this.categoryId, query).then(res => {
						this.resetSearch(res)
					}).catch(err => {
						this.loadingType = 0;
					})
				} else {
					console.log("getGoodList2" + this.categoryId)
					getPage(query).then(function(res) {
						if (res.status == 200 && res.data.length > 0)
							this.resetSearch(res.data);
					}).catch(err => {
						console.log("err" + JSON.stringify(err))
						that.loadingType = 0;
					})
				}

			},
			resetSearch: function(res) {
				if (res.status == 200 && res.data.length > 0) {
					for (var i = 0; i < res.data.length; i++) {
						res.data[i].baseUrl = getUrl();
						var prices = res.data[i].productPrices.sort(function(a, b) {
							return a.price > b.price
						})
						if (prices.length > 0) {
							res.data[i].maxPrice = prices[0].price;
							res.data[i].minPrice = prices[prices.length - 1].price;
						}
					}
				}
				console.log("attach" + JSON.stringify(res.attach));
				this.goodsList = this.goodsList.concat(res.data);
		
				this.page++;
				this.filterCategory = this.filterCategory.concat(res.attach)
				this.loadingType = 0;
				this.searchStatus = true;
				this.categoryFilter = false;
			},
			closeSearch: function() {
				uni.navigateBack()
			},
			openSortFilter: function(event) {
				let currentId = event.currentTarget.id;
				switch (currentId) {
					case 'categoryFilter':
						this.categoryFilter = !this.categoryFilter;
						this.currentSortType = 'HOTS';
						this.currentSortOrder = 'asc';
						break;
					case 'priceSort':
						let tmpSortOrder = 'asc';
						if (this.currentSortOrder === 'asc') {
							tmpSortOrder = 'desc';
						}
						this.categoryFilter = false;
						this.currentSortType = 'price';
						this.currentSortOrder = tmpSortOrder;
						this.getGoodList();
						break;
					default:
						// 综合排序
						this.categoryFilter = false;
						this.currentSortType = 'RECOMMENDATION';
						this.currentSortOrder = 'desc';
						this.getGoodList();
				}
			},
			// 清空关键词
			clearKeyword: function() {
				this.keyword = '';
				this.searchStatus = false;
				console.log("clearKeyword:" + this.searchStatus)
				this.page = 1;
				console.log("this.clearKeyword:" + this.searchStatus)
			},
			// 监听输入事件
			inputChange: function(e) {
				// debounce防抖 500ms
				console.log("input change....")
				if (this.timer) {
					clearTimeout(this.timer);
				}
				this.timer = setTimeout(() => {
					this.keyword = e.target.value;
					this.searchStatus = false;
					console.log("inputChange:" + this.searchStatus)
					this.getHelpKeyword();
				}, 500)
			},
			// 输入框获得焦点
			inputFocus: function() {
				this.searchStatus = false;
				this.goodsList = [];
				if (this.keyword) {
					this.getHelpKeyword();
				}

				if (this.isFirstLoad) {
					this.isFirstLoad = false;
					this.getGoodList();
				}
			},
			clearHistory: function() {
				this.historyKeyword = [];
				delProductHistory(this.userId);
			},
			getHelpKeyword: function() {
				this.getSearchKeyword({
					keyword: this.keyword,
					page: 1,
					limit: 10,
					orderBy: "createdStamp",
					sort: "desc"
				}).then(response => {
					if (response.status == 200 && response.data.length > 0) {
						this.helpKeyword = this.helpKeyword.concat(response.data);
					}
				});
			},

			// 关键词被点击
			onKeywordTap(event) {
				// console.log('点击关键词的event', event);
				this.getSearchResult(event.currentTarget.dataset.keyword);
			},
			// 上一个方法调用
			getSearchResult(keyword) {
				this.keyword = keyword;
				this.page = 1;
				this.goodsList = [];
				this.getGoodList();
			},
 		},
	}
</script>

<style>
	.search-header {
		/* position: fixed;
		top: 0; */
		width: 700upx;
		height: 91upx;
		display: flex;
		background: #fff;
		border-bottom: 1px solid rgba(0, 0, 0, .15);
		padding: 0 25upx;
		font-size: 29upx;
		color: #333;
	}

	.search-header .input-box {
		position: relative;
		margin-top: 16upx;
		float: left;
		width: 0;
		flex: 1;
		height: 59upx;
		line-height: 59upx;
		padding: 0 20upx;
		background: #f4f4f4;
	}

	.search-header .icon {
		position: absolute;
		top: 14upx;
		left: 20upx;
		width: 31upx;
		height: 31upx;
	}

	.search-header .del {
		position: absolute;
		top: 3upx;
		right: 10upx;
		width: 53upx;
		height: 53upx;
		z-index: 10;
	}

	.search-header .keywrod {
		position: absolute;
		top: 0;
		left: 40upx;
		width: 506upx;
		height: 59upx;
		padding-left: 30upx;
	}

	.search-header .right {
		margin-top: 24upx;
		margin-left: 31upx;
		margin-right: 6upx;
		width: 58upx;
		height: 43upx;
		line-height: 43upx;
		float: right;
	}

	.no-search {
		height: auto;
		/* margin-top: 91upx; */
	}

	.serach-keywords {
		background: #fff;
		width: 750upx;
		height: auto;
		overflow: hidden;
		margin-bottom: 20upx;
	}

	.serach-keywords .h {
		padding: 0 31.25upx;
		height: 93upx;
		line-height: 93upx;
		width: 95%;
		color: #999;
		font-size: 29upx;
	}

	.serach-keywords .title {
		display: block;
		width: 120upx;
		float: left;
	}

	.serach-keywords .icon {
		margin-top: 19upx;
		float: right;
		display: block;
		margin-left: 511upx;
		height: 55upx;
		width: 55upx;
	}

	.search-result {
		height: auto;
		/* margin-top: 91upx; */
	}

	.serach-keywords .b {
		width: 750upx;
		height: auto;
		overflow: hidden;
		padding-left: 31.25upx;
	}

	.serach-keywords .item {
		display: inline-block;
		width: auto;
		height: 48upx;
		line-height: 48upx;
		padding: 0 15upx;
		border: 1px solid #999;
		margin: 0 31.25upx 31.25upx 0;
		font-size: 24upx;
		color: #333;
	}

	.serach-keywords .item.active {
		color: #b4282d;
		border: 1px solid #b4282d;
	}

	.search-result-empty {
		width: 100%;
		height: 100%;
		padding-top: 300upx;
	}

	.search-result-empty .icon {
		margin: 0 auto;
		display: block;
		width: 240upx;
		height: 240upx;
	}

	.search-result-empty .text {
		display: block;
		width: 100%;
		height: 40upx;
		font-size: 28upx;
		text-align: center;
		color: #999;
	}
</style>
